package com.wedata;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Map;
import java.util.Set;

public class HttpUtils {

    private static final Logger LOGGER = LoggerFactory.getLogger(HttpUtils.class);

    public static JSONObject sendPost(String uri, JSONObject body){
        return sendRequest(uri,new JSONObject(),body,"POST");
    }

    public static JSONObject sendPost(String uri, JSONObject header, Object body){
        return sendRequest(uri,header,body,"POST");
    }
    public static JSONObject sendDelete(String uri, JSONObject header, JSONObject body){
        return sendRequest(uri,header,body,"DELETE");
    }

    public static JSONObject sendPut(String uri, JSONObject header, JSONObject body){
        return sendRequest(uri,header,body,"PUT");
    }

    public static JSONObject sendRequest(String uri, JSONObject header, Object body, String requestMethod){
        HttpURLConnection connection = null;
        try {
            URL url = new URL(uri);
            connection = (HttpURLConnection)url.openConnection();
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setRequestMethod(requestMethod);
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestProperty("Content-Type","application/json; charset=UTF-8");
            connection.setConnectTimeout(3000);// 10秒 连接超时时间（单位毫秒）
            connection.setReadTimeout(5000);// 5秒 读取数据超时时间（单位毫秒）

            //设置header
            if(header != null){
                final Set<String> keySet = header.keySet();
                for(String key:keySet) {
                    connection.setRequestProperty(key,header.getStr(key));
                }
            }
            connection.connect();
            LOGGER.info("sendPost uri=" + uri +",param="+ body + ",header=" + header);
            DataOutputStream out = new DataOutputStream(connection.getOutputStream());
            out.write(body.toString().getBytes());
            out.flush();
            out.close();

            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String lines;
            StringBuffer sb = new StringBuffer("");
            while((lines=reader.readLine())!=null){
                lines = new String(lines.getBytes(StandardCharsets.UTF_8));
                sb.append(lines);
            }
            reader.close();
            connection.disconnect();
            System.out.println("sendRequest result:" + sb);
            return new JSONObject(sb);
        }catch (SocketTimeoutException e){
            System.out.println("连接超时异常");
        }catch (Exception e){
            LOGGER.error("sendPost uri=" + uri +",param="+ body + ",header=" + header.toJSONString(0)+",happen exception.",e);
            //System.out.println("sendRequest uri=" + uri +",param="+ body.toJSONString(0) + ",header=" + header+",happen exception.");
            e.printStackTrace();
        }finally {
            if(connection != null){
                try {
                    connection.disconnect();
                }catch (Exception e){}
            }
        }
        return null;
    }
    /*public static JSONObject sendPost(String uri, JSONObject header, JSONArray body){
        HttpURLConnection connection = null;
        try {
            URL url = new URL(uri);
            connection = (HttpURLConnection)url.openConnection();
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setRequestMethod("POST");
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestProperty("Content-Type","application/json; charset=UTF-8");

            //设置header
            if(header != null){
                final Set<String> keySet = header.keySet();
                for(String key:keySet) {
                    connection.setRequestProperty(key,header.getStr(key));
                }
            }
            connection.connect();
            LOGGER.info("sendPost uri=" + uri +",param="+ body.toJSONString(0) + ",header=" + header);
            DataOutputStream out = new DataOutputStream(connection.getOutputStream());
            out.write(body.toJSONString(0).getBytes());
            out.flush();
            out.close();

            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String lines;
            StringBuffer sb = new StringBuffer("");
            while((lines=reader.readLine())!=null){
                lines = new String(lines.getBytes(StandardCharsets.UTF_8));
                sb.append(lines);
            }
            reader.close();
            connection.disconnect();
            //System.out.println("sendPost result:" + sb);
            return new JSONObject(sb);
        }catch (Exception e){
            //LOGGER.error("sendPost uri=" + uri +",param="+ body.toJSONString(0) + ",header=" + header.toJSONString(0)+",happen exception.",e);
            System.out.println("sendPost uri=" + uri +",param="+ body.toJSONString(0) + ",header=" + header+",happen exception.");
            e.printStackTrace();
        }finally {
            if(connection != null){
                try {
                    connection.disconnect();
                }catch (Exception e){}
            }
        }
        return null;
    }*/
    public static JSONObject doGet(String uri, Map<String, String> headers){
        HttpURLConnection connection = null;
        try {
            URL url = new URL(uri);
            connection = (HttpURLConnection)url.openConnection();
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setRequestMethod("GET");
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            //connection.setRequestProperty("Content-Type","application/json; charset=UTF-8");
            connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded utf-8");

            //设置header
            if(headers != null){
                final Set<String> keySet = headers.keySet();
                for(String key : keySet) {
                    connection.setRequestProperty(key,headers.get(key));
                }
            }

            connection.connect();
            //DataOutputStream out = new DataOutputStream(connection.getOutputStream());
            //out.write(body.toJSONString(0).getBytes());
            //out.flush();
            //out.close();

            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String lines;
            StringBuffer sb = new StringBuffer("");
            while((lines=reader.readLine())!=null){
                lines = new String(lines.getBytes(StandardCharsets.UTF_8));
                sb.append(lines);
            }
            reader.close();
            connection.disconnect();
            LOGGER.info("sendPost result:" + sb);
            return new JSONObject(sb);
        }catch (Exception e){
            System.out.println(e);
        }finally {
            if(connection != null){
                try {
                    connection.disconnect();
                }catch (Exception e){}
            }
        }
        return null;
    }
    public static JSONObject doGet(String uri){
        try {
            HttpRequest httpRequest = cn.hutool.http.HttpUtil.createGet(uri);
            HttpResponse httpResponse = httpRequest.execute();

            //System.out.println("doGet result:" + httpResponse.body());
            return new JSONObject(httpResponse.body());
        }catch (Exception e){
            System.out.println(e);
        }
        return null;
    }
    public static String getString(String uri){
        HttpURLConnection connection = null;
        try {
            HttpRequest httpRequest = cn.hutool.http.HttpUtil.createGet(uri);
            HttpResponse httpResponse = httpRequest.execute();
            return httpResponse.body();
        }catch (Exception e){
            System.out.println(e);
        }finally {
            if(connection != null){
                try {
                    connection.disconnect();
                }catch (Exception e){}
            }
        }
        return null;
    }
    public static JSONArray getList(String uri){
        HttpURLConnection connection = null;
        try {
            HttpRequest httpRequest = cn.hutool.http.HttpUtil.createGet(uri);
            HttpResponse httpResponse = httpRequest.execute();

            //System.out.println("doGet result:" + httpResponse.body());
            return new JSONArray(httpResponse.body());
        }catch (Exception e){
            System.out.println(e);
        }finally {
            if(connection != null){
                try {
                    connection.disconnect();
                }catch (Exception e){}
            }
        }
        return null;
    }

    public static String md5(String paramString) throws Exception {
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException ignored) {
            throw new Exception(ignored);
        }

        byte[] bytes = md5.digest(paramString.toString().getBytes("UTF-8"));
        StringBuilder sign = new StringBuilder();
        for (byte b : bytes) {
            String hex = Integer.toHexString(b & 0xFF);
            if (hex.length() == 1) {
                sign.append("0");
            }
            sign.append(hex);
        }
        return sign.toString();
    }

    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url 发送请求的 URL
     * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static JSONObject sendPostByForm(String url, String param)
    {
        PrintWriter out = null;
        BufferedReader in = null;
        StringBuilder result = new StringBuilder();
        try
        {
            System.out.println(url);
            System.out.println(param);
            Long startTime = System.currentTimeMillis();
            LOGGER.info("sendPost - {}, param - {}", url, param);
            URL realUrl = new URL(url);
            URLConnection conn = realUrl.openConnection();
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setRequestProperty("Accept-Charset", "utf-8");
            conn.setRequestProperty("contentType", "application/x-www-form-urlencoded utf-8");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            out = new PrintWriter(conn.getOutputStream());
            out.print(param);
            out.flush();
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
            String line;
            while ((line = in.readLine()) != null)
            {
                result.append(line);
            }
            JSONObject jsonObject = new JSONObject(result);
            Long entTime = System.currentTimeMillis();
            LOGGER.info("sendPost {}, 耗时 {}, result - {}", url, entTime-startTime, jsonObject);
            return jsonObject;
        }
        catch (ConnectException e)
        {
            LOGGER.error("调用HttpUtils.sendPost ConnectException, url=" + url + ",param=" + param, e);
        }
        catch (SocketTimeoutException e)
        {
            LOGGER.error("调用HttpUtils.sendPost SocketTimeoutException, url=" + url + ",param=" + param, e);
        }
        catch (IOException e)
        {
            LOGGER.error("调用HttpUtils.sendPost IOException, url=" + url + ",param=" + param, e);
        }
        catch (Exception e)
        {
            LOGGER.error("调用HttpsUtil.sendPost Exception, url=" + url + ",param=" + param, e);
        }
        finally
        {
            try
            {
                if (out != null)
                {
                    out.close();
                }
                if (in != null)
                {
                    in.close();
                }
            }
            catch (IOException ex)
            {
                LOGGER.error("调用in.close Exception, url=" + url + ",param=" + param, ex);
            }
        }

        return new JSONObject(result);
    }
}

